import { defineStore } from 'pinia'
import { useFlickerStore } from './flicker'
// import { useExplosionStore } from './explosion'
import { useProtectionStore } from './protection'
import { useRecordStore } from './gameRecord'

export const useGameLoopStore = defineStore('loop', {
  state: () => ({
    frameTiming: 0, // 一帧时长 ms 游戏系统的时间基准
    maxFPS: Infinity, // 限制帧率 Infinity表示当前不限制
    slow: 1,
  }),
  actions: {
    gameLoop() {
      let lastTime = performance.now()
      let requestId = null
      let accumulation = 0
      
      const breath = () => {
        const now = performance.now()
        const diff = now - lastTime
        this.frameTiming = diff
        lastTime = now

        const recordStore = useRecordStore()

        if (recordStore.pause.status) {
          recordStore.pauseAnimation(diff)
        } else {
          accumulation += diff
          if(accumulation > 1000 / this.maxFPS) {
            const ft = accumulation / this.slow
            this.frameTiming = ft

            // 更新游戏状态
            const flickerStore = useFlickerStore()
            // const explosionStore = useExplosionStore()
            const protectionStore = useProtectionStore()

            flickerStore.playFlicker(ft)
            // explosionStore.playExplosion(ft)
            recordStore.initPause()
            recordStore.stageAnim(ft)
            protectionStore.playProtection(ft)

            accumulation = 0
          }
        }
        requestId = requestAnimationFrame(breath)
      }

      requestId = requestAnimationFrame(breath)
    }
  }
})
